<template>
  <div class="blood-collection-system">
    <!-- 护士操作界面 -->
    <div class="nurse-panel">
      <h2>采血叫号系统 - 护士操作端</h2>
      <div class="control-panel">
        <div class="station-select" style="width:200px;">
          <label>采血窗口：</label>
          <el-select v-model="currentStation" @change="getBusiness" style="width:80px;">
            <el-option v-for="station in stations" :key="station.id" :label="station.winName" :value="station.winCode">
            </el-option>
          </el-select>
        </div>
        <el-button @click="callNextPatient" type="primary">叫号</el-button>
        <el-button @click="recallCurrent" type="primary">重呼</el-button>
        <el-button @click="skipCurrent" type="primary">过号</el-button>
        <el-button @click="pauseCurrent(1)" type="warning" v-if="getStationState(currentStation)==1">暂停</el-button>
        <el-button @click="pauseCurrent(2)" type="warning" v-if="getStationState(currentStation)==2">启用</el-button>
        <el-button @click="closeCurrent" type="danger" v-if="getStationState(currentStation)==1">关闭</el-button>
        <el-button @click="pauseCurrent(3)" type="danger" v-if="getStationState(currentStation)==0">开启</el-button>
        <!-- &nbsp; &nbsp; &nbsp; &nbsp;待采血人：{{patientQueueText}} -->
      </div>

      <div class="current-patient" v-if="currentCalledPatient">
        <h3>当前患者</h3>
        <div class="patient-info">
          <p>号码：<span class="highlight">{{ currentCalledPatient.businessNo }}</span></p>
          <p>窗口：<span class="highlight">{{ currentCalledPatient.winName }}</span></p>
        </div>
      </div>

      <div class="queue-list">
        <h3>等候队列</h3>
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>号码</th>
              <th>姓名</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(patient, index) in patientsQueue" :key="patient.id">
              <td>{{ index + 1 }}</td>
              <td>{{ patient.businessNo }}</td>
              <td>{{ patient.userName }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { initWebSocket } from '@/utils/websocket';
import axios from 'axios';


export default {
  setup() {
    // 采血窗口设置
    const stations = ref([]);

    // 当前操作的窗口
    const currentStation = ref('001');

    // 患者队列
    const patientsQueue = ref([]);

    // 当前叫号的患者
    const currentCalledPatient = ref(null);

    // 当前日期和时间
    const currentDate = ref('');
    const currentTime = ref('');

    // 更新当前时间
    const updateTime = () => {
      const now = new Date();
      currentDate.value = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        weekday: 'long'
      });
      currentTime.value = now.toLocaleTimeString('zh-CN', { hour12: false });
    };

    // 定时器
    let timer;

    onMounted(() => {
      updateTime();
      timer = setInterval(updateTime, 1000);
      getWindow();
      getBusiness();
      initWebSocket(getQueenLists);
    });

    function getWindow() {
      axios.get(window.apiUrl.VITE_SERVER_URL + '/callNum/bigScreenGetWindow')
        .then(response => {
          stations.value = response.data.data;
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    }

    onBeforeUnmount(() => {
      clearInterval(timer);
    });

    function getQueenLists(data) {
      console.log(data);
      if (data.type == 'getNum') {
        patientsQueue.value.push(JSON.parse(data.message));
      }
    }

    // 计算等待时间
    const calculateWaitTime = (patient) => {
      const waitTime = (Date.now() - patient.timestamp) / (60 * 1000);
      return Math.round(waitTime);
    };

    function getBusiness() {
      axios.get(window.apiUrl.VITE_SERVER_URL + '/callNum/bigScreenGetBusiness', { params: { currentWindow: currentStation.value, state: 5 } })
        .then(response => {
          patientsQueue.value = response.data.data;
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    }

    // 获取窗口名称
    const getStationName = (winCode) => {
      const station = stations.value.find(s => s.winCode == winCode);
      return station ? station.name : '';
    };
    // 获取窗口名称
    const getStationState = (winCode) => {
      const station = stations.value.find(s => s.winCode == winCode);
      return station ? station.isEnable : '';
    };

    // 叫号下一个患者
    const callNextPatient = () => {
      // 如果有当前正在采血的患者，先结束
      if (currentCalledPatient.value) {
        currentCalledPatient.value.state = '10';
        patientsQueue.value.splice(currentCalledPatient.value, 1);
      }

      // 获取当前窗口的下一个患者
      const nextPatient = patientsQueue.value.find(p =>
        p.winCode === currentStation.value && p.state == '5'
      );

      if (nextPatient) {
        console.log(nextPatient);
        nextPatient.state = '10';
        currentCalledPatient.value = nextPatient;
        axios.post(window.apiUrl.VITE_SERVER_URL + '/callNum/nurseCallNum', currentCalledPatient.value)
          .then(response => {
            console.log(`请${nextPatient.winCode}到${getStationName(currentStation.value)}采血`);
          })
          .catch(error => {
            console.error('There was an error!', error);
          });
        // 播报叫号信息（实际应用中这里可以调用语音API）
        console.log(`请${nextPatient.winCode}到${getStationName(currentStation.value)}采血`);
      } else {
        alert('当前窗口没有等候的患者');
      }
    };

    // 重新呼叫当前患者
    const recallCurrent = () => {
      if (currentCalledPatient.value) {
        console.log(`重新呼叫：请${currentCalledPatient.value.winCode}到${getStationName(currentStation.value)}采血`);
      }
    };

    // 过号当前患者
    const skipCurrent = () => {
      if (currentCalledPatient.value) {
        currentCalledPatient.value.state = '10';
        axios.post(window.apiUrl.VITE_SERVER_URL + '/callNum/nurseCallNum', currentCalledPatient.value)
          .then(response => {
            currentCalledPatient.value = null;
          })
          .catch(error => {
            console.error('There was an error!', error);
          });
      }
    };

    const pauseCurrent = (state) => {
      axios.get(window.apiUrl.VITE_SERVER_URL + '/callNum/business/pauseWindow', { params: { winCode: currentStation.value, state: state }, headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') } })
        .then(response => {
          getWindow();
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    }

    const closeCurrent = () => {
      axios.get(window.apiUrl.VITE_SERVER_URL + '/callNum/business/closeWindow', { params: { winCode: currentStation.value }, headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') } })
        .then(response => {
          getWindow();
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    }


    // 计算属性
    const patientQueueText = computed(() => {
      console.log(patientsQueue.value);
      const datas = patientsQueue.value.filter(p => p.winCode == currentStation.value && p.state == '5').map(m => m.businessNo);
      return datas.join(",");
    });

    return {
      stations,
      currentStation,
      patientsQueue,
      currentCalledPatient,
      currentDate,
      currentTime,
      calculateWaitTime,
      getStationName,
      callNextPatient,
      recallCurrent,
      skipCurrent,
      getBusiness,
      pauseCurrent,
      closeCurrent,
      patientQueueText,
      getStationState
    };
  }
};
</script>

<style scoped>
.blood-collection-system {
  font-family: 'Microsoft YaHei', sans-serif;
  max-width: 500px;
  margin: 0 auto;
}

/* 护士操作面板样式 */
.nurse-panel {
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.control-panel {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.station-select select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.call-button,
.recall-button,
.skip-button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.call-button {
  background-color: #4caf50;
  color: white;
}

.recall-button {
  background-color: #2196f3;
  color: white;
}

.skip-button {
  background-color: #f44336;
  color: white;
}

.call-button:hover {
  background-color: #45a049;
}

.recall-button:hover {
  background-color: #0b7dda;
}

.skip-button:hover {
  background-color: #da190b;
}

.current-patient {
  background-color: #e8f5e9;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.patient-info {
  font-size: 18px;
}

.highlight {
  font-weight: bold;
  color: #d32f2f;
  font-size: 20px;
}

.queue-list table {
  width: 100%;
  border-collapse: collapse;
}

.queue-list th,
.queue-list td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.queue-list th {
  background-color: #4caf50;
  color: white;
}

.queue-list tr:nth-child(even) {
  background-color: #f2f2f2;
}

.queue-list tr:hover {
  background-color: #ddd;
}

/* 大屏显示样式 */
.display-screen {
  background-color: #f0f0f0;
  padding: 20px;
  border-radius: 8px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
  background-color: #d32f2f;
  color: white;
  padding: 15px;
  border-radius: 5px;
}

.header h1 {
  margin: 0;
  font-size: 32px;
}

.current-date,
.current-time {
  font-size: 24px;
  margin-top: 10px;
}

.calling-info {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.calling-station {
  text-align: center;
  padding: 0 20px;
}

.calling-station h2 {
  color: #d32f2f;
  margin-bottom: 10px;
}

.called-number {
  font-size: 36px;
  font-weight: bold;
  color: #d32f2f;
  margin: 10px 0;
  min-height: 50px;
}

.waiting-info {
  font-size: 18px;
  color: #666;
}

.waiting-queue {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.waiting-queue h2 {
  text-align: center;
  color: #d32f2f;
  margin-bottom: 20px;
}

.queue-columns {
  display: flex;
  justify-content: space-around;
}

.queue-column {
  flex: 1;
  padding: 0 15px;
}

.queue-column h3 {
  text-align: center;
  color: #333;
  border-bottom: 2px solid #d32f2f;
  padding-bottom: 10px;
}

.queue-numbers {
  min-height: 200px;
}

.queue-number {
  font-size: 20px;
  margin: 8px 0;
  padding: 5px;
  background-color: #f5f5f5;
  text-align: center;
  border-radius: 3px;
}

.more-patients {
  font-size: 16px;
  color: #666;
  text-align: center;
  margin-top: 10px;
}

.footer-message {
  margin-top: 20px;
  background-color: #333;
  color: white;
  padding: 10px;
  border-radius: 5px;
}

.footer-message marquee {
  font-size: 18px;
}
</style>